import { useSelector } from 'react-redux';

import { configureStore } from '@reduxjs/toolkit';
import { persistReducer, persistStore } from 'redux-persist';
import storage from 'redux-persist/lib/storage/'; //  localStorage 作为存储介质
import sessionStorage from 'redux-persist/lib/storage/session'; //sessionStorage  作为存储介质
import reducers, { actions } from './reducers';
// 配置 redux-persist 的持久化选项
const persistConfig = {
  key: 'root', // 存储在 localStorage 中的键名
  storage: sessionStorage, // 使用 localStorage 作为存储介质
};
// 创建一个持久化的 reducer
const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

export const persistor = persistStore(store);

type IStore = Omit<ReturnType<typeof store.getState>, '_persist'>;

export const useStore = <T>(value: (store: IStore) => T) => {
  return useSelector(value);
};

/** redux 封装 */
export default class Store {
  static store = store;

  static useStore = useStore;

  static actions = actions;

  static dispatch = this.store.dispatch;

}
